package com.fingard.dsp.bank.directbank.bocom13.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 用来产生文件的MD5码
 *
 * @author aps-nig
 */
public class JavaMD5 {
    private static final int BUFFER = 8192;
    private static final byte hex[] = "0123456789ABCDEF".getBytes();

    /**
     * 将16进制字符串转换成字节数组
     *
     * @param hexstr
     * @return
     */
    public static byte[] hexStr2Bytes(String hexstr) {
        byte b[] = new byte[hexstr.length() >> 1];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) (parse(c0) << 4 | parse(c1));
        }

        return b;
    }

    private static int parse(char c) {
        if (c >= 'a')
            return (c - 97) + 10 & 0xf;
        if (c >= 'A')
            return (c - 65) + 10 & 0xf;
        else
            return c - 48 & 0xf;
    }

    /**
     * 将字节数组转换成16进制字符串
     *
     * @param b
     * @return
     */
    public static String bytes2HexStr(byte b[]) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++)
            sb.append(byteToHexString(b[i]));
        return sb.toString();
    }

    /**
     * 将字节转换成16进制字符串
     *
     * @param b
     * @return
     */
    private static String byteToHexString(byte b) {
        byte buff[] = new byte[2];
        buff[0] = hex[b >> 4 & 0xf];
        buff[1] = hex[b & 0xf];
        return new String(buff);
    }

    public static String generateFileMD5(String fileName) throws NoSuchAlgorithmException, IOException {
        int n = 0;
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(fileName));
            byte data[] = new byte[BUFFER];
            while ((n = fis.read(data, 0, BUFFER)) != -1)
                md.update(data, 0, n);
            fis.close();
            byte[] md5 = md.digest();
            return bytes2HexStr(md5);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }
}
